package com.dm.cloud.tkmybatis.service;

import cn.hutool.core.util.StrUtil;
import com.dm.cloud.core.service.user.UserUtil;
import com.dm.cloud.basepo.po.BasePo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;

import java.util.Date;
import java.util.Properties;

/**
 * @Author sg
 * @ClassName BasePOInterceptor
 * @Description mybatis拦截insert、update填充公共字段
 * @Date 2021/08/18 15:17
 */

@Slf4j
@Intercepts({
        @Signature(
                type = Executor.class,
                method = "update",
                args = {MappedStatement.class, Object.class})
})
public class BasePOInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        Object userId = null;
        try {
            userId = UserUtil.currentUid();
        }catch (Exception e){
            userId = "-1";
        }
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        // 只处理参数为BasePO子类的情况
        Object param = invocation.getArgs()[1];
        if (param == null || !BasePo.class.isAssignableFrom(param.getClass())) {
            return invocation.proceed();
        }

        BasePo entity = (BasePo) param;
        // 获取Sql执行类型
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        switch (sqlCommandType) {
            case INSERT:
                if(StrUtil.isEmptyIfStr(entity.getId()) || entity.getId().trim().length()==0){
                    entity.setId(null);
                }
                entity.setCreateTime(new Date());
                entity.setUpdateTime(new Date());
                entity.setCreateUser(userId != null ? userId.toString() : null);
                entity.setUpdateUser(userId != null ? userId.toString() : null);
                break;
            case UPDATE:
                if (entity.getUpdateTime() == null) {
                    entity.setUpdateTime(new Date());
                }
                entity.setUpdateUser(userId != null ? userId.toString() : null);
                break;
            default:
                break;
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}